package com.mzmarket.market.console.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mzmarket.market.console.domain.ValueInfo;
import com.mzmarket.market.module.entity.User;
import com.mzmarket.market.module.service.UserService;
import com.mzmarket.market.module.utils.JwtCookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(
            @RequestParam String phone,
            @RequestParam String password,
            HttpServletResponse res,
            HttpServletRequest req
    ) throws IOException {
        User user;

        try {
            user = userService.getByPhone(phone);
        } catch (Exception e) {
            return "手机号输入格式错误";
        }

        if (user == null) {//判断用户是否存在
            return "用户不存在";
        } else {
            //判断密码是否匹配
            if (user.getPassword().equals(DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes()))) {
                /*方法一、把信息放到服务端中的session中*/
                HttpSession session = req.getSession(); // 返回新或已存在会话
                /* ② 把业务数据写进 Session */
                session.setAttribute("phone", user.getPhone());
                session.setAttribute("expireTime", System.currentTimeMillis() + 3600_000);


                /*方法二、把信息放到用户端cookie中*/
                //使用JWT加密
                String token = JwtCookieUtil.encrypt(phone);
                //将加密好的token封装
                ValueInfo valueInfo = new ValueInfo().setToken(token);
                // 将封装好的token对象序列化,并使用base64编码
                ObjectMapper objectMapper = new ObjectMapper();
                String cookieValue = Base64.getEncoder().encodeToString(objectMapper.writeValueAsString(valueInfo).getBytes());
                //设置cookie
                Cookie cookie = new Cookie("token", cookieValue);
                cookie.setPath("/");           // 所有路径都有效
                cookie.setMaxAge(24 * 60 * 60); // 1天有效
                cookie.setHttpOnly(true);      // JS不能读取，提高安全性
                res.addCookie(cookie);
                return "登录成功";
            } else {
                return "密码不正确";
            }
        }
    }
}
